package com.koo.modules.base.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.koo.framework.listener.UserListener;
import com.koo.modules.base.entity.User;
import com.koo.modules.base.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Description：
 * @Author: charlin
 * @Date: 2022/12/28 16:13
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public void exportUser(HttpServletResponse response, String operName) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //设置响应内容类型
            response.setCharacterEncoding("utf-8");//编码
            // 设置文件名, ps:把字符串中所有的'+'替换成'%20'，在URL中%20代表空格
            String fileName = URLEncoder.encode("用户表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");//设置响应头

            List<User> listUser = this.initUsers();
            ExcelWriter writer = EasyExcel.write(response.getOutputStream(), User.class).build();//获取写出流
            WriteSheet sheet = EasyExcel.writerSheet("用户").build();//创建表格，设置表格页名称
            writer.write(listUser, sheet);//读出
            writer.finish();//关闭流
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean importUser(MultipartFile file, boolean updateSupport, String operName) {
        try {
            UserListener excelListener = new UserListener(this, updateSupport, operName);
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            //EasyExcel.read(哪个文件).sheet(那张sheet表).head(表头什么样子).headRowNumber(表头占几行).registerReadListener(处理数据的监听器类).doRead()
            EasyExcel.read(file.getInputStream(), User.class, excelListener).sheet(0).head(User.class).headRowNumber(1).doRead();
            System.out.println(excelListener.getErrorUsers());
            System.out.println(excelListener.getSuccess());
            System.out.println(excelListener.getFail());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    private List<User> initUsers() {
        List<User> list = new ArrayList<>();
        list.add(new User(1, "tom", "tom", "I am tom"));
        list.add(new User(2, "jack", "jack", "I am jack"));
        return list;
    }


    @Override
    public User queryUserById(Integer id) {
        return null;
    }

    @Override
    public boolean updateUser(User user) {
        return false;
    }

    @Override
    public boolean addUser(User user) {
        return false;
    }
}


